package com.le.basic.StackAndQueue;

/**
 * 用数组结构实现大小固定的栈
 */
public class Code_01_ArrayToStack {
   int[] stack;
   int next;

    public Code_01_ArrayToStack(int size) {
        if (size < 0){
            throw new IllegalArgumentException();
        }
        stack = new int[size];
        next = 0;
    }

    public void push(int num){
        if (next == stack.length){
           throw new IndexOutOfBoundsException();
        }
        stack[next++] = num;
    }

    public int pop(){
        if (next == 0){
            throw new IndexOutOfBoundsException();
        }
        return stack[--next];
    }

    public int peek(){
        if (next <= 0){
            throw new IndexOutOfBoundsException();
        }
        return stack[next - 1];
    }

    public static void main(String[] args) {
        Code_01_ArrayToStack stack = new Code_01_ArrayToStack(3);
        stack.push(1);
        stack.push(2);
        stack.push(3);

        System.out.println(stack.pop());
        System.out.println(stack.pop());

        stack.push(4);

        System.out.println(stack.peek());
    }

}
